package com.itheima.system.controller;


import com.github.pagehelper.Page;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.system.pojo.Device;
import com.itheima.system.pojo.Order;
import com.itheima.system.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * 平台设备管理
 */
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        try {
            List<Device> deviceList = deviceService.findAll();
            return new Result(true, StatusCode.OK, "查询成功", deviceList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable Long id) {
            Device device = deviceService.findById(id);
            if (device==null){
                return new Result(false, StatusCode.ERROR, "查询失败");
            }
            return new Result(true, StatusCode.OK, "查询成功", device);
    }

    /**
     * 条件查询
     * @param name
     * @return
     */
    @GetMapping("/search/{name}")
    public Result findList(@PathVariable String name) {
        try {
            List<Device> deviceList = deviceService.findList(name);
            return new Result(true, StatusCode.OK, "查询成功", deviceList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, StatusCode.OK, "查询成功");
        }
    }

    /**
     *分页+条件查询
     * @param
     * @return
     */
    @GetMapping("/findPage/{page}/{size}")
    public Result findPage(@PathVariable Integer page,@PathVariable Integer size,@RequestParam Map searchMap) {
        System.out.println(searchMap);
        Page<Device> pageList = deviceService.findPage(page,size,searchMap);
        PageResult pageResult = new PageResult(pageList.getTotal(),pageList.getResult());
        if (pageResult==null){
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }

    /**
     * 添加
     * @param order
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Order order){
        System.out.println(order);
        if (order==null){
            return new Result(false,StatusCode.ERROR,"添加失败");
        }else {
            deviceService.add(order);
            return new Result(true,StatusCode.OK,"添加成功");
        }
    }
}